package com.kun.video.ui.control.button;

import com.kun.video.AbstractApplication;
import com.kun.video.context.ContextService;
import com.kun.video.thread.ComThreadPool;
import com.kun.video.ui.dialog.ConfirmDialog;
import com.kun.video.util.ComUtil;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.DialogPane;
import javafx.scene.layout.HBox;
import javafx.stage.Window;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Consumer;

/**
 * TODO
 *
 * @author gzc
 * @since 2025/3/20
 **/
public class AlertButton extends AbstractButton {
    private final static Logger log = LoggerFactory.getLogger(AlertButton.class);
    protected final ConfirmDialog dialog;
    protected Consumer<Boolean> resultConsumer;
    protected Consumer<ConfirmDialog> layoutConsumer;

    public AlertButton(String buttonText) {
        this(buttonText, null, null, AbstractApplication.getAppStage());
    }

    public AlertButton(String buttonText, Node svgGraphic, String tipText, Window owner) {
        super(buttonText, svgGraphic, tipText);
        dialog = new ConfirmDialog(buttonText, owner);
    }

    public void layoutHandler(Consumer<ConfirmDialog> layoutConsumer) {
        if (layoutConsumer != null) {
            layoutConsumer.accept(dialog);
        }
    }

    public void showLayoutHandler(Consumer<ConfirmDialog> layoutConsumer) {
        this.layoutConsumer = layoutConsumer;
    }

    public void resultHandler(Consumer<Boolean> resultConsumer) {
        this.resultConsumer = resultConsumer;
    }

    @Override
    public ButtonEvent createButtonEvent() {
        return () -> ComUtil.uiThreadRun(() -> {
            onActionProperty().setValue(event -> {
                try {
                    if (this.layoutConsumer != null) {
                        this.layoutConsumer.accept(dialog);
                    }
                    boolean result = dialog.showAndWaitResult();
                    if (this.resultConsumer != null) {
                        this.resultConsumer.accept(result);
                    }
                } catch (Exception e) {
                    log.error("打开弹窗失败", e);
                }
            });
            // 主要用来实现fxml文件
            EventHandler<ActionEvent> eventHandler = onActionProperty().getValue();
            if (eventHandler != null) {
                eventHandler.handle(new ActionEvent());
            }
        });
    }

}
